<template>
  <div class="width-100">
    <!--跳转页面-->
    <div v-if="action.reType === 'pageCtl'" class="flex-com mar-btm">
      <span class="label-title font-weight-bold iconfont icon-branch"></span>
      <el-select v-model="action.value.value" size="mini" class="width-input" @change="pageEvent(action)">
        <el-option
          v-for="(page, index) in curPageHandler.pages" :key="index"
          :label="page.name" :value="page.id"></el-option>
      </el-select>
    </div>
    <!--控制设备-->
    <div v-if="action.reType === 'deviceCtl'">
      <!--选设备-->
      <div class="flex-com mar-btm">
        <span class="label-title font-weight-bold iconfont icon-branch"></span>
        <el-select
          v-model="action.value.device" size="mini"
          placeholder="设备名称" class="width-input"
          @change="(value) => choseDevice(value, action)">
          <el-option
            v-for="(item, index) in deviceList" :key="index"
            :label="`${item.controlId ? item.controlId : '-'}-${item.deviceOtherName?item.deviceOtherName:item.deviceName}`"
            :value="item._id"></el-option>
        </el-select>
      </div>
      <!--设备命令/分自定义命令和设备命令-->
      <div class="flex-com mar-btm" v-if="action.value.device">
        <span class="label-title font-weight-bold iconfont icon-branch"></span>
        <el-select
          v-model="action.command" placeholder="设备命令"
          size="mini" class="width-input"
          @change="(value) => genCommChanged(value, action)">
          <el-option-group
            v-for="(group, idx) in findDeviceCommands(action)"
            :key="idx" :label="group.label">
            <el-option
              v-for="(item, idx) in group.options" :key="idx"
              :label="item.commandName"
              :value="group.value === 0 ? `${item.id}.custom` : `${item.methodName}.device`">
            </el-option>
          </el-option-group>
        </el-select>
      </div>
      <!--无参数/有参数-->
      <div v-if="action.currentParams">
        <div v-for="(params, index) in action.currentParams" :key="index">
          <!--有参数/有枚举/先选组件变量，再判断有枚举选枚举，没枚举选别的-->
          <div class="flex-com mar-btm">
            <span class="label-title font-color-primary font-weight-bold el-icon-edit-outline"></span>
            <span>--选择{{params.paramAlias}}--</span>
          </div>
          <SelectVariable :action="params" @changeState="(val) => deviceEvent(action,val)"
                          @showPicker="showPicker">
          </SelectVariable>
        </div>
      </div>
    </div>
    <!--组合命令/结束组合命令-->
    <div v-if="['sceneCtl','stopScene'].includes( action.reType)" class="flex-com mar-btm">
      <span class="label-title font-weight-bold iconfont icon-branch"></span>
      <el-select v-model="action.value.value" size="mini" class="width-input" @change="sceneEvent(action)">
        <el-option
          v-for="(item, index) in globalScenesList" :key="index"
          :label="item.name" :value="item.key"></el-option>
      </el-select>
    </div>
    <!--修改组件-->
    <div v-if="action.reType === 'editVar'">
      <div class="flex-com mar-btm">
        <span class="label-title font-weight-bold iconfont icon-branch"></span>
        <el-input
          :value="getAtomicAttr(action.atomic, 'name')"
          disabled size="mini" placeholder="选择组件" class="width-input"></el-input>
        <span class="label-title font-color-primary font-weight-bold cursor-pointer"
              @click="showPicker([action, 'atomic'])">选择</span>
      </div>
      <div v-if="action.atomic">
        <div class="flex-com mar-btm">
          <span class="label-title font-weight-bold iconfont icon-branch"></span>
          <el-select
            v-model="action.state" size="mini"
            placeholder="选择修改项" class="width-input"
            @change="(value) => changePorts(value, action)">
            <el-option
              v-for="(state, index) in getAtomicAttr(action.atomic, 'ports')" :key="index"
              :label="state.name" :value="state.key"></el-option>
          </el-select>
        </div>
        <div v-if="action.state">
          <!--显隐/固定true/false-->
          <div v-if="action.state === 'visible'" class="flex-com mar-btm">
            <span class="label-title font-weight-bold iconfont icon-branch"></span>
            <el-select
              v-model="action.value.value" size="mini"
              placeholder="值绑定" class="width-input"
              @change="stateEvent(action)">
              <el-option
                v-for="(item, index) in visibleCtl.visibleOption" :key="index"
                :label="item.name" :value="item.key"></el-option>
            </el-select>
          </div>
          <!--状态/固定state1/2-->
          <div v-else-if="action.state === 'state'" class="flex-com mar-btm">
            <span class="label-title font-weight-bold iconfont icon-branch"></span>
            <el-select
              v-model="action.value.value" size="mini"
              placeholder="状态" class="width-input"
              @change="stateEvent(action)">
              <el-option
                v-for="(item, index) in getAtomicAttr(action.atomic, 'states')" :key="index"
                :label="item.stateName" :value="item.id"></el-option>
            </el-select>
          </div>
          <!--其他变量/3种情况-->
          <div v-else>
            <SelectVariable
              :iftttLogic="iftttLogic"
              :action="action"
              @showPicker="showPicker"
              @changeState="stateEvent">
            </SelectVariable>
            <!--真值反馈选设备变量 特殊处理-->
            <div v-if="action.autoType === 3">
              <IftttFiled :iftttLogic="iftttLogic" :rule-form="action.value"></IftttFiled>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!--情景查询-->
    <div v-if="action.reType === 'sceneQuery'">
      <div class="flex-com mar-btm">
        <span class="label-title font-weight-bold iconfont icon-branch"></span>
        <el-select
          size="mini" class="width-input"
          v-model="action.value.value"
          filterable
          allow-create
          clearable
          default-first-option
          placeholder="按回车键输入值"
          @change="sceneQueryEvent(action)">
          <el-option
            label="子会议"
            value="subMeetings">
          </el-option>
          <el-option
            v-for="item in sceneOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </div>
    </div>
    <!--房间属性设置-->
    <div v-if="action.reType === 'setRoomAttribute'">
      <div class="flex-com mar-btm">
        <span class="label-title font-weight-bold iconfont icon-branch"></span>
        <el-select
          size="mini" class="width-input"
          v-model="action.value.key.value"
          filterable
          allow-create
          clearable
          default-first-option
          placeholder="按回车键输入属性">
          <el-option
            v-for="item in sceneOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </div>
      <div class="flex-com mar-btm">
        <span class="label-title font-weight-bold iconfont icon-branch"></span>
        <InputsComponent :inputsObject="action.value.value"></InputsComponent>
      </div>
    </div>
    <!--修改全局变量-->
    <div v-if="action.reType === 'editGlobalVar'">
      <div class="flex-com mar-btm">
        <span class="label-title font-weight-bold iconfont icon-branch"></span>
        <el-select v-model="action.key" size="mini" class="width-input"
                   @change="(value) => changeGlobal(value, action)">
          <el-option
            v-for="(global, index) in globalVarList" :key="index"
            :label="global.name" :value="global.key"></el-option>
        </el-select>
      </div>
      <div v-if="action.key">
        <SelectVariable :action="action" @changeState="globalEvent" @showPicker="showPicker"></SelectVariable>
      </div>
    </div>
    <!--字符串插入-->
    <div v-if="action.reType === 'logicStringInsert'">
      <div class="flex-com">
        <span class="label-title"></span>
        <span class="font-size-12">关联文本</span>
      </div>
      <SelectVariable
        :action="action.value.text"
        @showPicker="showPicker"
        @changeState="insetTextEvent(action.value.text, action)"></SelectVariable>
      <div class="flex-com">
        <span class="label-title"></span>
        <span class="font-size-12">选择插入字符</span>
      </div>
      <SelectVariable
        :action="action.value.character"
        @showPicker="showPicker"
        @changeState="insetTextEvent(action.value.character)"></SelectVariable>
    </div>
    <!--字符串删除-->
    <div v-if="action.reType === 'logicStringDelete'">
      <div class="flex-com">
        <span class="label-title"></span>
        <span class="font-size-12">关联文本</span>
      </div>
      <SelectVariable
        :action="action.value.text" @showPicker="showPicker"
        @changeState="insetTextEvent(action.value.text, action)"></SelectVariable>
    </div>
    <!--关联调用另一个事件-->
    <div v-if="action.reType === 'relatedAction'">
      <div class="flex-com mar-btm">
        <span class="label-title font-weight-bold iconfont icon-branch"></span>
        <el-input
          :value="getAtomicAttr(action.atomic, 'name')" disabled
          size="mini" placeholder="选择组件" class="width-input"></el-input>
        <span class="label-title font-color-primary font-weight-bold cursor-pointer"
              @click="showPicker([action, 'atomic'])">选择</span>
      </div>
      <div class="flex-com mar-btm">
        <span class="label-title font-weight-bold iconfont icon-branch"></span>
        <el-select
          v-model="action.value.value" size="mini" class="width-input"
          placeholder="请选择组件事件"
          @change="() => relatedEvent(action)">
          <el-option
            v-for="(event, index) in getAtomicAttr(action.atomic, 'events')" :key="index"
            :label="event.name" :value="event.key ? event.key : event.eventType"></el-option>
        </el-select>
      </div>
    </div>
    <!--函数事件-->
    <div v-if="action.reType === 'logicCmd'">
      <div class="flex-com mar-btm">
        <span class="label-title font-weight-bold iconfont icon-branch"></span>
        <span class="font-size-12"></span>
        <span class="label-title font-color-primary font-weight-bold cursor-pointer"
              @click="openLogicDialog(action)">输入函数</span>
      </div>
    </div>
    <!--状态处理-->
    <div v-if="action.reType === 'iftttLogic'">
      <div class="flex-com mar-btm">
        <span class="label-title font-weight-bold iconfont icon-branch"></span>
        <span class="font-size-12"></span>
        <span class="label-title font-color-primary font-weight-bold cursor-pointer"
              @click="openStateDialog(action)">状态处理</span>
      </div>
    </div>
    <!--多状态处理-->
    <div v-if="action.reType === 'iftttLogicList'">
      <div class="flex-com mar-btm">
        <span class="label-title font-weight-bold iconfont icon-branch"></span>
        <span class="font-size-12"></span>
        <span class="label-title font-color-primary font-weight-bold cursor-pointer"
              @click="openStateListDialog(action)">多状态处理</span>
      </div>
    </div>
    <!--udp发送数据-->
    <div v-if="action.reType === 'netDataSend'">
      <div class="flex-com mar-btm">
        <span class="label-title font-weight-bold iconfont icon-branch"></span>
        <el-select v-model="action.value.type" size="mini" class="width-input">
          <el-option label="UDP" value="udp"></el-option>
          <el-option label="TCP" value="tcp"></el-option>
        </el-select>
      </div>
      <div class="flex-com">
        <span class="label-title"></span>
        <span class="font-size-12">ip地址</span>
      </div>
      <SelectVariable
        :action="action.value.ip"
        @showPicker="showPicker"
        @changeState="insetTextEvent(action.value.ip, action)"></SelectVariable>
      <div class="flex-com">
        <span class="label-title"></span>
        <span class="font-size-12">端口号</span>
      </div>
      <SelectVariable
        :action="action.value.port"
        @showPicker="showPicker"
        @changeState="insetTextEvent(action.value.port, action)"></SelectVariable>
      <div class="flex-com">
        <span class="label-title"></span>
        <span class="font-size-12">数据-默认ASCII数据，HEX需加前缀<b class="font-color-primary">HEX:</b></span>
      </div>
      <SelectVariable
        :action="action.value.data"
        @showPicker="showPicker"
        @changeState="insetTextEvent(action.value.data, action)"></SelectVariable>
    </div>
    <!--内置功能-->
    <div v-if="action.reType ==='padDefaultCmd'">
      <div class="flex-com mar-btm">
        <span class="label-title font-weight-bold iconfont icon-branch"></span>
        <el-select
          v-model="action.value.value"
          size="mini" class="width-input"
          filterable
          allow-create
          clearable
          default-first-option
          placeholder="按回车键输入值"
          @change="padDefaultCmdEvent(action)">
          <el-option
            v-for="(item, index) in padDefaultCmdList" :key="index"
            :label="item.label" :value="item.value"></el-option>
        </el-select>
      </div>
    </div>
    <!--用户无操作-->
    <div v-if="action.reType === 'userNoAction'">
      <div class="flex-com">
        <span class="label-title"></span>
        <span class="font-size-12">触发时间(s)</span>
      </div>
      <SelectVariable
        :action="action.value.time"
        @showPicker="showPicker"
        @changeState="insetTextEvent(action.value.time, action)"></SelectVariable>
      <div class="flex-com">
        <span class="label-title"></span>
        <span class="font-size-12">触发动作</span>
      </div>
      <slot name="selectAction"></slot>
    </div>
    <!--显示提示信息-->
    <div v-if="action.reType === 'showToast'">
      <div class="flex-com">
        <span class="label-title"></span>
        <span class="font-size-12">显示时间(ms)</span>
      </div>
      <div class="flex-com mar-btm">
        <span class="label-title font-weight-bold iconfont icon-branch"></span>
        <el-input-number
          v-model="action.value.time.value" :step="1000" :min="0"
          size="mini" class="width-input"></el-input-number>
        <span>ms</span>
      </div>
      <div class="flex-com">
        <span class="label-title"></span>
        <span class="font-size-12">显示文本</span>
      </div>
      <div class="flex-com mar-btm">
        <span class="label-title font-weight-bold iconfont icon-branch"></span>
        <el-input
          v-model="action.value.text.value"
          size="mini" class="width-input"></el-input>
      </div>
    </div>
    <!--释放会议信息-->
    <div v-if="action.reType === 'concludeMeeting'">
      <div class="flex-com">
        <span class="label-title"></span>
        <span class="font-size-12">会议id</span>
      </div>
      <SelectVariable
        :action="action.value.meetingId"
        @showPicker="showPicker"
        @changeState="insetTextEvent(action.value.meetingId, action)"></SelectVariable>
    </div>
    <el-dialog
      :visible.sync="logicDialog"
      :close-on-click-modal="false"
      :append-to-body="true"
      title="函数输入" width="1000px"
      @close="closeLogicEvent">
      <el-collapse>
        <el-collapse-item title="平板处理逻辑说明" name="1">
          <div v-for="(item,index) in funcType" :key="index">
            <p class="pad-lft-5 text-bold">{{item.label}}</p>
            <ul class="mar-top-5">
              <li class="mar-btm-5" v-for="(func,index) in item.options " :key="index">
                {{func.name}}<code>{{func.desc}}</code></li>
            </ul>
          </div>
        </el-collapse-item>
      </el-collapse>
      <CodeEditor v-if="reFresh" v-model="advancedProgramForm.logicFunc" class="mar-top"></CodeEditor>
      <div class="mar-top text-align-right">
        <el-button type="info" size="small" @click="closeLogicEvent">取消</el-button>
        <el-button type="primary" size="small" @click="logicEventFormSubmit">提交</el-button>
      </div>
    </el-dialog>
    <!--状态处理-->
    <el-dialog
      :visible.sync="stateDialog"
      :close-on-click-modal="false"
      :append-to-body="true"
      title="状态处理" width="800px">
      <IftttState :ruleForm="stateAction" ref="iftttState"></IftttState>
      <div class="mar-top text-align-right">
        <el-button type="info" size="small" @click="closeStateEvent">取消</el-button>
        <el-button type="primary" size="small" @click="stateEventFormSubmit">提交</el-button>
      </div>
    </el-dialog>
    <!--多状态处理-->
    <el-dialog
      :visible.sync="stateListDialog"
      title="多状态处理" width="800px"
      :close-on-click-modal="false"
      :append-to-body="true">
      <div
        style="position: absolute; top: 50px; right: 16px"
        class="font-color-primary font-size-12 font-weight-bold cursor-pointer"
        @click="addEvent">
        <i class="iconfont icon-tianjia"></i><span class="mar-lft-5">添加规则</span>
      </div>
      <el-tabs v-model="activeRuleIdx" type="border-card" class="mar-top-10">
        <el-tab-pane
          v-for="(action, idx) in stateListAction" :key="idx" :name="`${idx}`">
          <template slot="label">
            <i class="header-icon el-icon-info font-size-14 ">规则{{idx + 1}}</i>
          </template>
          <IftttState :ruleForm="action" ref="iftttState">
            <template slot="copyRule">
              <span class="el-icon-copy-document cursor-pointer font-hover-primary" @click="copyEvent(idx)"></span>
              <span class="el-icon-delete cursor-pointer font-hover-danger mar-lft-10" @click="deleteEvent(idx)"></span>
            </template>
          </IftttState>
        </el-tab-pane>
      </el-tabs>
      <div class="mar-top text-align-right">
        <el-button type="info" size="small" @click="closeStateListEvent">取消</el-button>
        <el-button type="primary" size="small" @click="stateListEventFormSubmit">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import InputsComponent from "@/page/IDE/editor/dock/component/InputsComponent.vue";
  import IftttFiled from "@/page/IDE/editor/dock/component/IftttFiled.vue";
  import SelectVariable from "@/page/IDE/editor/dock/component/SelectVariable.vue";
  import {mapActions, mapState} from "vuex";
  import {confirmHandle, deepCopy, formatJsCode, generateUID, getAtomicAttr, messageHandle} from "@/utils";
  import {getStorage, setStorage, StorageKey} from "@/config/sessions";
  import {dftPadCode} from "@/config/string";
  import {commonConfig, dataTypeArray} from "@/config/common";
  import CodeEditor from "@/components/IDE/CodeEditor.vue";
  import IftttState from "@/page/IDE/editor/dock/component/IftttState.vue";

  export default {
    name: "EventComponent",
    components: {IftttState, CodeEditor, SelectVariable, IftttFiled, InputsComponent},
    props: {
      widget: {
        type: Object,
        default: () => {
          return {};
        }
      },
      action: {
        type: Object,
        default: () => {
          return {};
        },
      },
      iftttLogic: {
        type: Boolean,
        default: () => {
          return false;
        },
      },
    },
    data() {
      return {
        dataTypeArray: dataTypeArray,
        commonConfig: commonConfig,
        funcType: [
          {
            label: "功能函数",
            options: [
              {name: "获取变量的值:", desc: "dynamic var1 = getVar(key)"},
              {name: "设置变量的值:", desc: "setVar(key,value)"},
              {name: "控制情景:", desc: "controlScene(sceneKey)"},
              {name: "控制设备:", desc: "controlDevice(data)"},
            ],
          },
          {
            label: "key有以下几种定义",
            options: [
              {name: "设备状态key:", desc: "如'm120601.power'"},
              {name: "组件状态key:", desc: "如'7CL577x7iLmXqHpi-tFEGiJUO99KhlXGMWmT72AxtE0yBjiVi.visible'"},
              {name: "系统key:", desc: "如'm120601.power'"},
              {name: "情景key:", desc: "如'm120601.power'"},
              {name: "自定义key:", desc: "如customerKey1"},
            ],
          },
          {
            label: "value有以下几种定义",
            options: [
              {name: "bool类型(布尔):", desc: "如true,false"},
              {name: "int类型(整数):", desc: "如1,2,3"},
              {name: "double类型(小数):", desc: "如1.0,2.111,0.999"},
              {name: "string类型(字符串):", desc: "如'm120601.power'"},
              {name: "自定义key:", desc: "如abc','123'"},
            ],
          },
          {
            label: "sceneKey有以下几种定义",
            options: [
              {name: "开启系统的唯一标志:", desc: "如systemOn"},
              {name: "关闭系统的唯一标志:", desc: "如systemOff"},
            ],
          },
          {
            label: "data为Map类型,结构如下",
            options: [
              {name: "", desc: formatJsCode(dftPadCode.func1)},
            ],
          },
          {
            label: "如控制设备通道开关",
            options: [
              {name: "", desc: formatJsCode(dftPadCode.func2)},
            ],
          },
        ],
        //控制显隐
        visibleCtl: {
          visibleOption: [
            {name: "显示", key: true},
            {name: "隐藏", key: false},
          ],
        },
        //控制设备
        deviceCtl: {
          currentDevice: {}, //当前选中设备
          customDevice: {}, //当前自定义命令
        },
        activeNames: ["onTap0"],
        currentAction: {},
        currentAtomic: '',
        currentWidgetId: '',
        curPickerId: '',
        showCustomEventDialog: false,
        customEventFormRules: {
          customName: [
            {required: true, message: '请填写事件名称', trigger: ['blur', 'change']}
          ],
        },
        customEventForm: {},
        customEventFormRef: 'customEventFormRef',
        logicDialog: false,
        advancedProgramForm: {
          logicFunc: formatJsCode(dftPadCode.codeFunc)
        },
        logicAction: {},
        reFresh: true,
        getAtomicAttr: getAtomicAttr,
        stateDialog: false,
        stateListDialog: false,
        stateAction: {},
        stateListAction: [],
        sceneOptions: [
          {
            value: 'curGroupCmd',
            label: '场景'
          },
          {
            value: 'occupied',
            label: '房间占用'
          },
          {
            value: 'autoSharing',
            label: '自动共享'
          },
          {
            value: 'systemOn',
            label: '开启系统'
          },
        ],
        padDefaultCmdList: [{
          value: 'showDeviceStatus',
          label: '显示设备状态'
        },
          {
            value: 'goToConfigPage',
            label: '进入设置页'
          },
          {
            value: 'showMeetingList',
            label: '显示所有会议'
          },
          {
            value: 'showMiniControlPage',
            label: '显示告警页面'
          }
        ],
        dragList: [],
        activeStateNames: 0,
        activeRuleIdx: '0'
      };
    },
    watch: {
      relAction: {
        handler(val) {
          this.dragList = val;
        },
        deep: true,
        immediate: true
      },
      'widgetPickerInfo.selectWidgetId': {
        handler(selectWidgetId) {
          if (!selectWidgetId) return;
          const {pickerId = ''} = this.widgetPickerInfo;
          if (this.curPickerId !== pickerId) return;
          if (this.currentWidgetId === selectWidgetId) return;
          if (this.currentAtomic === 'toAtomic') {
            this.$set(this.currentAction, 'toAtomic', selectWidgetId);
          } else {
            this.currentAction.atomic = selectWidgetId;
          }
          // 如果当前选中的目标组件发生变更，则清空该动作相关配置值
          this.currentAction.type && this.resetAtomic(this.currentAction);
          this.$forceUpdate();
        }
      }
    },
    computed: {
      ...mapState({
        globalDeviceList: (state) => state.ide.globalDeviceList,
        globalVarList: (state) => state.ide.globalVarList,
        globalScenesList: (state) => state.ide.globalScenesList,
        widgetPickerInfo: state => state.ide.widgetPickerInfo,
        curPageHandler: state => state.ide.curPageHandler,
      }),
      deviceList() {
        //组合自定义命令和设备命令到一个组
        return this.globalDeviceList.map((device) => {
          const commandList = [];
          const {customCommand, commands} = device;
          if (customCommand && customCommand.length > 0) {
            commandList.push({
              label: "自定义命令",
              options: customCommand,
              value: 0,
            });
          }
          if (commands && commands.length > 0) {
            commonConfig.commandType.forEach((type) => {
              const filterCommands = commands.filter((command) => command.commandType === type.value)
              if (filterCommands.length > 0) {
                commandList.push({
                  label: type.label,
                  options: filterCommands,
                  value: type.value,
                });
              }
            });
          }
          device.commandList = commandList || [];
          return device;
        });
      },
    },
    methods: {
      ...mapActions(['updateWidgetPickerInfo']),
      onEnd() {
        this.$emit('dragEvent', this.dragList);
      },
      /**跳转页面事件 */
      pageEvent(action) {
        action.name = "跳转页面";
        action.value.type = "string";
      },
      /**内置功能事件*/
      padDefaultCmdEvent(action) {
        action.name = "内置功能";
        action.value.type = "string";
      },
      /**组合命令事件 */
      sceneEvent(action) {
        if (action.reType === 'stopScene') {
          action.name = "结束组合命令";
        } else {
          action.name = "组合命令";
        }
        action.value.type = "relatedScene";
      },
      /**控制设备系列事件 */
      resetControlDevice(item) {
        item.command = "";
        item.currentParams = [];
        item.value.method = "";
        item.value.params = {};
      },
      resetControlCommand(item) {
        item.currentParams = [];
        item.value.method = "";
        item.value.params = {};
        item.autoType = 0;
      },
      choseDevice(val, action) {
        //重新选设备时，如果不是同一类设备或者是同一类设备，但是参数不一样 则清空
        if (action.command) {
          const stateVal = action.command.split(".")[0];
          const device = this.deviceList.find((item) => {
            return item._id === val;
          }) || {};
          const currentParams = device.commands.find(item => item.methodName === stateVal)
          if (currentParams === undefined || currentParams.params.length !== action.currentParams.length) {
            this.resetControlDevice(action);
          }
        }
        // if (!action.isCopy) {
        //   this.resetControlDevice(action);
        // }
        this.deviceCtl.currentDevice = this.deviceList.find((item) => {
          return item._id === val;
        });
      },
      // 动态根据设备id加载设备命令 并同步参数
      findDeviceCommands(action) {
        const commandList = this.deviceList.find((item) => {
          return item._id === action.value.device;
        });
        //查找控制id
        //这一步主要是为了匹配通用协议到设备协议 设备协议可能参数没有
        //因为currentParams保存到数据库中，如果设备协议更改了参数，则枚举列表要重新关联到currentParams中
        //controlId为m000000 就是通用协议和设备协议小组件虚拟设备
        if (commandList!==undefined &&commandList.controlId && commandList.controlId === 'm000000' && action.currentParams && action.currentParams.length > 0) {
          //拿当前设备的当前参数列表
          const currentParams = this.findCommandParams(action.value.device, action.command);
          //创建当前参数映射列表
          const bMap = new Map(currentParams.map(item => [item.paramKey, item]));
          action.currentParams.forEach((itemA, index) => {
            const matchedItemB = bMap.get(itemA.paramKey);
            // 如果存在匹配项，则替换 action.currentParams的枚举为新的参数枚举
            if (matchedItemB) {
              action.currentParams[index] = {...itemA, enumList: matchedItemB.enumList}; // 合并两个对象，b中的属性会覆盖a中的同名属性
            } else {
              //如果新的参数没有这个参数项 枚举就为空
              action.currentParams[index] = {...itemA, enumList: []}
            }
          });
        }
        return commandList ? commandList.commandList : [];
      },
      // 拿当前命令的当前参数
      findCommandParams(deviceId, command) {
        const stateVal = command.split(".")[0];
        const device = this.deviceList.find((item) => {
          return item._id === deviceId;
        }) || {};
        const stateCommand = device.commands ? device.commands.find(item => item.methodName === stateVal) : {};
        return stateCommand.params || [];
      },
      genCommChanged(val, action) {
        this.$forceUpdate();
        this.resetControlCommand(action);
        //以防万一回显时重新拿选中的设备
        this.deviceCtl.currentDevice = this.deviceList.find((item) => {
          return item._id === action.value.device;
        });
        const state = val.split(".")[1];
        const stateVal = val.split(".")[0];
        //判断有无参数
        if (state !== "device") {
          // 发送自定义命令
          this.deviceCtl.customDevice = this.deviceCtl.currentDevice.customCommand.find(item => item.id === stateVal);
          action.name = "设备控制";
          action.value.method = "sendOriginData";
          action.value.params = {
            data: {
              type: "relatedDevice",
              value: `${this.deviceCtl.currentDevice._id}.${this.deviceCtl.customDevice.id}`,
            },
          };
        } else {
          //发送设备命令
          const stateCommand = this.deviceCtl.currentDevice.commands.find(item => item.methodName === stateVal);
          action.currentParams = deepCopy(stateCommand.params);
          if (action.currentParams.length === 0 && action.command) {
            this.deviceEvent(action);
          }
        }
      },
      transformDevice(autoType, type) {
        //autoType是0固定值、1组件变量、2全局变量 type是固定值里面的类型 string\bool\int
        if (autoType === 0) {
          return type || "string";
        } else if (autoType === 1) {
          return "relatedAtomic";
        } else if (autoType === 2) {
          return "relatedGlobal";
        } else {
          return "string";
        }
      },
      // 有枚举有参数情况
      deviceEvent(action, val) {
        this.$forceUpdate();
        action.value.method = action.command.split(".")[0];
        action.name = "控制设备";
        const params = {};
        for (let key in action.currentParams) {
          params[action.currentParams[key].paramKey] = {
            type: this.transformDevice(action.currentParams[key].autoType, action.currentParams[key].type),
            value: action.currentParams[key].value,
          };
        }
        action.value.params = params;
      },
      /***修改组件 */
      stateEvent(action) {
        action.name = "修改组件";
        action.key = `${action.atomic}.${action.state}`;
        action.value.type = this.transformType(action);
      },
      /**情景查询 */
      sceneQueryEvent(action) {
        action.name = "情景查询";
        action.value.type = 'string';
      },
      /***修改全局变量 */
      globalEvent(action) {
        this.$forceUpdate();
        action.name = "修改全局变量";
        action.value.type = this.transformType(action);
      },
      // 字符插入事件
      insetTextEvent(item, action) {
        item.type = this.transformType(item);
        //关联文本带出光标
        if (item.name === '关联文本') {
          action.value.index.value = `${action.value.text.toAtomic}.selection`;
          action.value.index.type = action.value.text.type;
        }
        //用户无操作的触发时间为固定值时 type为int
        if (item.name === '延迟时间' && item.autoType === 0) {
          action.value.time.type = 'int';
        }
        this.$forceUpdate();
      },
      // 关联事件
      relatedEvent(action) {
        action.value.type = 'string';
      },
      // 重置原子组件
      changePorts(value, item) {
        const ports = getAtomicAttr(item.atomic, 'ports');
        item.portsType = ports.find(item => item.key === value).type;
        this.resetAtomic(item);
      },
      //更改全局变量
      changeGlobal(value, item) {
        item.portsType = this.globalVarList.find(item => item.key === value).type;
        this.resetAtomic(item);
        this.$forceUpdate()
      },
      resetAtomic(item) {
        if (item.type === "deviceCtl") {
          item.value.params = {};
        } else if (item.state === 'visible' || item.state === 'state') {
          delete item.autoType;
          delete item.toAtomic;
          // item.value = {};
          item.key = `${item.atomic}.${item.state}`;
        } else if (item.reType === 'editGlobalVar') {
          //全局变量不需要改变key
          item.value = {};
        } else if (item.reType === 'relatedAction') {
          item.key = null;
          item.value = {};
        } else {
          item.value = {};
          item.key = `${item.atomic}.${item.state}`;
        }
      },
      transformType(action) {
        let type;
        if (action.autoType === 2) {
          type = "relatedGlobal";
        } else if (action.autoType === 1) {
          type = "relatedAtomic";
        } else if (action.state === "state") {
          type = "int";
        } else if (action.state === "visible") {
          type = "bool";
        } else {
          type = action.portsType || "string";
        }
        return type;
      },
      showPicker(action) {
        this.currentAction = action[0];
        this.currentAtomic = action[1];
        this.currentWidgetId = action[1] === 'toAtomic' ? action[0].toAtomic : action[0].atomic;
        this.curPickerId = generateUID();
        this.updateWidgetPickerInfo({
          show: true,
          pickerId: this.curPickerId,
          selectWidgetId: this.currentWidgetId
        });
      },
      //函数输入事件
      openLogicDialog(action) {
        this.logicAction = action;
        this.logicDialog = true;
        this.advancedProgramForm.logicFunc = action.value.value ? action.value.value : formatJsCode(dftPadCode.logic);
        this.reFreshChild();
      },
      closeLogicEvent() {
        this.logicDialog = false;
        this.advancedProgramForm.logicFunc = '';
        this.$nextTick(() => {
          this.reFresh = false;
        });
      },
      //嵌入dialog的子组件不更新方法
      reFreshChild() {
        this.reFresh = false;
        this.$nextTick(() => {
          this.reFresh = true;
        });
      },
      logicEventFormSubmit() {
        this.logicAction.value.type = 'string';
        this.logicAction.value.value = this.advancedProgramForm.logicFunc;
        this.logicDialog = false;
      },
      openStateListDialog(action) {
        this.stateListDialog = true;
        this.stateListAction = action.value.actions;
        if (this.stateListAction.length === 0) {
          const list = {
            key: null,
            name: "自定义逻辑",
            type: "iftttLogic",
            value: {
              conditions: [{
                value1: {
                  key: '',
                  type: "relatedAtomic",
                  atomic: this.widget.id,
                  name: '',
                },
                operator: '',
                value2: {
                  name: '',
                  key: '',
                  type: 'string',
                  value: ''
                }
              }],
              actions: [],
              elseActions: [],
              enable: true,
              andOr: 'and'
            }
          };
          this.stateListAction.push(list);
        }
      },
      openStateDialog(action) {
        this.stateDialog = true;
        this.stateAction = action;
        //第一次状态处理需赋初始值
        if (Object.keys(this.stateAction.value).length === 0) {
          this.stateAction.value = {
            conditions: [{
              value1: {
                key: '',
                type: "relatedAtomic",
                atomic: this.widget.id,
                name: '',
              },
              operator: '',
              value2: {
                name: '',
                key: '',
                type: 'string',
                value: ''
              }
            }],
            actions: [],
            elseActions: [],
            enable: true,
            andOr: 'and'
          };
        }
      },
      closeStateEvent() {
        this.stateDialog = false;
        // this.stateAction.value = {};
      },
      stateEventFormSubmit() {
        const verify = this.$refs.iftttState.verify();
        if (!verify) return;
        this.stateDialog = false;
      },
      // 复制规则
      copyEvent(index) {
        const callback = this.stateListAction[index];
        if (!callback) return;
        this.stateListAction.splice(index, 0, deepCopy(callback));
        this.activeRuleIdx = `${this.stateListAction.length - 1}`;
      },
      // 删除规则
      deleteEvent(index) {
        confirmHandle({label: `确定要删除吗?`}).then(() => {
          this.stateListAction.splice(index, 1);
          if (this.stateListAction[index - 1]) {
            this.activeRuleIdx = `${index - 1}`;
          }
        }).catch(() => {
        });
      },
      //添加真值反馈事件
      addEvent() {
        const verify = this.verify();
        if (!verify) return;
        this.activeStateNames = this.stateListAction.length
        this.stateListAction.push({
          name: "自定义逻辑", //类似if else的作用 温度>18
          key: null,
          type: "iftttLogic",
          delay: 0,
          value: {
            conditions: [],
            actions: [],
            elseActions: [],
            enable: true,
            andOr: 'and'
          },
        });
        this.activeRuleIdx = `${this.stateListAction.length - 1}`;
      },
      verify() {
        const lastValue = this.stateListAction[this.stateListAction.length - 1];
        const conditions = lastValue ? lastValue.value.conditions : [];
        const lastConditions = conditions[conditions.length - 1];
        if (lastValue !== undefined && lastConditions !== undefined && lastConditions.value2.value.length === 0 && lastConditions.value2.autoType !== 4) {
          //判断条件属性必须 判断上一条内容为空 ，类型不是空值类型
          this.$notify({
            message: '请填写完整的判断条件！',
            type: 'warning',
            duration: 3000,
          });
          return false;
        } else if (lastValue !== undefined && lastValue.value.actions.length === 0 && lastValue.value.elseActions.length === 0) {
          //满足和不满足条件必须其中一个
          this.$notify({
            message: '请至少填写一项条件满足或不满足后触发的操作！',
            type: 'warning',
            duration: 3000,
          });
          return false;
        } else {
          return true;
        }
      },
      closeStateListEvent() {
        this.stateListDialog = false;
        // this.stateAction.value = {};
      },
      stateListEventFormSubmit() {
        const verify = this.verify();
        if (!verify) return;
        this.stateListDialog = false;
      },
    },
  }
</script>
<style lang="less" scoped>
  /**子组件分别继承不同父组件的样式 */
  .drag-mover {
    cursor: move;
  }

  .divider {
    height: 8px;
    background: @colorGray96;
    margin-left: -15px;
    margin-right: -15px;
  }

  .event-dock-container {
    height: calc(100vh - 90px);
    overflow: auto;

    .pad-divider {
      padding: 20px 10px;
      box-sizing: border-box;
      border-bottom: 1px solid #dadce5;
    }

    .title {
      margin: 0;
      color: @colorGray10;
      font-size: 14px;
    }

    .flex-com {
      display: flex;
      align-items: center;
      gap: 10px;
    }

    .wrap {
      flex-wrap: wrap;
      gap: 2px;
    }


    .label-title {
      min-width: 42px;
      color: #12131A;
      font-size: 14px;
      text-align: center;
    }


    .width-input {
      width: 100%;

      /deep/ .el-input__inner {
        background: #f7f8fa;
      }
    }

  }

  .ifttt-cont {
    width: 100%;

    .flex-com {
      display: flex;
      align-items: center;
      gap: 10px;
    }

    .label-title {
      min-width: 42px;
      color: @colorGray10;
      font-size: 14px;
      text-align: center;
      flex-shrink: 0;
    }

    .width-input {
      width: 350px;

      /deep/ .el-input__inner {
        width: 100%;
        background: #fff;
      }
    }

    &::-webkit-scrollbar {
      display: none;
    }

  }

  /deep/ .el-collapse-item__content {
    padding-bottom: 10px;
  }

  /deep/ .el-collapse-item__wrap {
    border-bottom: 10px solid #EBEEF5;
  }

  .header-icon {
    color: #e0572d;
  }
</style>
